﻿using Business.Service;
using Model;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json;

namespace MvcAppWeb.Controllers
{
    public class PrintDeliOrderController : BaseDataController
    {
        //
        // GET: /PrintDeliOrder/

        public ActionResult PrintDeliOrder()
        {
            if (Session["UserInfo"] == null) return RedirectToAction("LogOn", "Account");
            else
            {
                AppUserList model = (AppUserList)Session["UserInfo"];
                return View(model);

            }
        }
        public JsonResult RechargeCardList()
        {
            var retData = new object();
            Business.NewCommon nc = new Business.NewCommon();
            retData = nc.GetRechargeCardList().ToList();
            return Json(retData);
        }

        public JsonResult AreaList(int IsSetAll)
        {
            var retData = new object();
            Business.NewCommon nc = new Business.NewCommon();
            retData = nc.GetAreaListFromDelivery(IsSetAll).ToList();
            return Json(retData);
        }

        ///<summary>
        ///查询订单打印信息
        ///</summary>
        ///<returns></returns>
        public JsonResult InitJsonResult(string startDate, string OrderNo = "", string selArea = "0", string batchno = "0", string OrderStatus = "0",
            string OrderFrom = "", string OrderEnd = "", string GOODSCODE = "")
        {

            string where = " where 1=1 and a.orderstatus in(1,2,5,6) and a.SiteID is not null";
            int page = int.Parse(Request["page"].ToString());
            int rows = int.Parse(Request["rows"].ToString());
            int total = 0;

            if (startDate != "")
            {
                DateTime RationDate;
                if (DateTime.TryParse(startDate, out RationDate))
                {
                    where += " and CONVERT(varchar(100), a.DeliveryBeginDate, 23)='" + RationDate.ToString("yyyy-MM-dd") + "' ";
                }
                else
                    where += " and 1=0";
            }
            if (OrderNo != "")
            {
                where += "   and a.orderno='" + OrderNo + "'";
            }
            if (!selArea.Equals("0"))
            {
                where += " and a.siteid='" + selArea.Trim() + "' ";
            }
            if (!batchno.Equals("0"))
            {
                where += " and a.batchno='" + batchno + "' ";
            }
            int orderFrom_End = 0;
            if (int.TryParse(OrderFrom, out orderFrom_End))
            {
                where += " and a.batchsubno>=" + OrderFrom;
            }
            if (int.TryParse(OrderEnd, out orderFrom_End))
            {
                where += " and a.batchsubno<=" + OrderEnd;
            }
            if (!string.IsNullOrEmpty(GOODSCODE))
            {
                GOODSCODE = GOODSCODE.Substring(0, GOODSCODE.Length - 1);
                where += @" and exists(select 1 from (
                                    select t1.GoodsNo as goodscode from
                                        (select GoodsNo from Deli_OrderDetail a1 where a1.OrderNo=a.orderno) t1
                                        left join ECERP_Product_4 P4 ON t1.GoodsNo = P4.ProductNo
                                        where ( P4.IsSpliter = 0 or  P4.IsSpliter is NULL )
                                    union ALL
                                        select FM.CombSN as goodscode
                                        from (select GoodsNo from Deli_OrderDetail a1 where a1.OrderNo=a.orderno) t1 
							            LEFT Join ECERP_Product_4 P4 ON t1.GoodsNo = P4.ProductNo
                                        Left Join ECERP_Formulacombination FM ON P4.ProductNo = FM.FormulaSN
							            where P4.IsSpliter = 1) te where te.goodscode in(" + GOODSCODE + "))";
            }
            if (!OrderStatus.Equals("0"))
            {
                if (OrderStatus == "1")//1为未取消2已取消
                    where += " and a.orderstatus<>2 ";
                else
                    where += " and a.orderstatus=2 ";
            }

            var retData = new object();
            BPrintOrderInfo db = new BPrintOrderInfo();
            retData = db.GetPrintDeliOrderList(page, rows, out total, where).ToList();
            Dictionary<string, object> json = new Dictionary<string, object>();
            json.Add("total", total);
            json.Add("rows", retData);
            return Json(json);
        }

        [HttpPost]
        public string ExporterExcelDetail(string RationStartDate, string OrderNo = "", string DeliverArea = "0", string selBatch = "0",
            string OrderStatus = "0", string OrderFrom = "", string OrderEnd = "", string GOODSCODE = "", string IsByTickNo="0", string Ispreview = "0")
        {
            string sjson = string.Empty;
            BPrintOrderInfo db = new BPrintOrderInfo();
            int intOrderFrom = 0;
            int intOrderEnd = 0;
            if (int.TryParse(OrderFrom, out intOrderFrom)) { }
            if (int.TryParse(OrderEnd, out intOrderEnd)) { }
            GOODSCODE = Request["hiddenGOODSCODE"];

            string where = " where 1=1 and a.orderstatus in(1,2,5,6) and a.SiteID is not null";

            if (RationStartDate != "")
            {
                DateTime RationDate;
                if (DateTime.TryParse(RationStartDate, out RationDate))
                {
                    where += " and CONVERT(varchar(100), a.DeliveryBeginDate, 23)='" + RationDate.ToString("yyyy-MM-dd") + "' ";
                }
                else
                    where += " and 1=0";
            }
            if (OrderNo != "")
            {
                where += "   and a.orderno='" + OrderNo + "'";
            }
            if (!DeliverArea.Equals("0"))
            {
                where += " and a.siteid='" + DeliverArea.Trim() + "' ";
            }
            if (!selBatch.Equals("0"))
            {
                where += " and a.batchno='" + selBatch + "' ";
            }
            int orderFrom_End = 0;
            if (int.TryParse(OrderFrom, out orderFrom_End))
            {
                where += " and a.batchsubno>=" + OrderFrom;
            }
            if (int.TryParse(OrderEnd, out orderFrom_End))
            {
                where += " and a.batchsubno<=" + OrderEnd;
            }
            if (!OrderStatus.Equals("0"))
            {
                if (OrderStatus == "1")//1为未取消2已取消
                    where += " and a.orderstatus<>2 ";
                else
                    where += " and a.orderstatus=2 ";
            }
            string where1 = where + " and ( P4.IsSpliter = 0 or  P4.IsSpliter is NULL )";
            string where2 = where + " and P4.IsSpliter = 1";
            if (!string.IsNullOrEmpty(GOODSCODE))
            {
                GOODSCODE = GOODSCODE.Substring(0, GOODSCODE.Length - 1);
                where1 = where + " and t1.goodsno in(" + GOODSCODE + ")";
                where2 = where + " and FM.CombSN in(" + GOODSCODE + ")";
                where += @" and exists(select 1 from (
                                    select t1.GoodsNo as goodscode from
                                        (select GoodsNo from Deli_OrderDetail a1 where a1.OrderNo=a.orderno) t1
                                        left join ECERP_Product_4 P4 ON t1.GoodsNo = P4.ProductNo
                                        where ( P4.IsSpliter = 0 or  P4.IsSpliter is NULL )
                                    union ALL
                                        select FM.CombSN as goodscode
                                        from (select GoodsNo from Deli_OrderDetail a1 where a1.OrderNo=a.orderno) t1 
							            LEFT Join ECERP_Product_4 P4 ON t1.GoodsNo = P4.ProductNo
                                        Left Join ECERP_Formulacombination FM ON P4.ProductNo = FM.FormulaSN
							            where P4.IsSpliter = 1) te where te.goodscode in(" + GOODSCODE + "))";
            }
            //判断排序方式：IsByTickNo为1时按票号、配送时段升序，否则按批次号
            if (IsByTickNo == "1")
                where += " order by SUBSTRING(a.deliveryperiod, 11,12),a.TICKETNO";
            else
                where += " order by CONVERT(INTEGER,batchno),CONVERT(INTEGER, batchsubno)";


            List<PrintOrderInfo> lstPrintOrderInfo = db.GetPrintDeliOrderList(where).ToList();
            List<OrderInfoDetail> listDetail = db.GetPrintDeliOrderDetailList1(where1).ToList();
            listDetail.AddRange(db.GetPrintDeliOrderDetailList2(where2).ToList());

            listDetail = (from a in listDetail
                          group a by new { a.GOODSCODE, a.GOODSNAME, a.PRODUCTNAME, a.SKUNAME, a.SHEETID }
                  into g
                          select new OrderInfoDetail
                          {
                              GOODSCODE = g.Key.GOODSCODE,
                              PRODUCTNAME = g.Key.PRODUCTNAME.Trim(),
                              SKUNAME = g.Key.SKUNAME.Trim(),
                              //销售名等于SKU名时只显示销售名，否则显示销售名(SKU名)
                              GOODSNAME = (!string.IsNullOrWhiteSpace(g.Key.SKUNAME) && !string.IsNullOrWhiteSpace(g.Key.PRODUCTNAME) && g.Key.SKUNAME.Trim() != g.Key.PRODUCTNAME.Trim()) ?
                              string.Format("{0}({1})", g.Key.PRODUCTNAME.Trim(), g.Key.SKUNAME.Trim()) : g.Key.PRODUCTNAME.Trim()
                              ,
                              SHEETID = g.Key.SHEETID,
                              QTY = g.Sum(_ => _.QTY)
                          }).ToList();


            //List<PrintOrderInfo> lstPrintOrderInfo = db.GetPrintDeliOrderList(RationStartDate, OrderNo, DeliverArea, selBatch, OrderStatus, intOrderFrom, intOrderEnd).ToList();//获取分拣单信息
            //List<OrderInfoDetail> listDetail = db.GetPrintDeliOrderDetailList(RationStartDate, OrderNo, DeliverArea, selBatch, OrderStatus, intOrderFrom, intOrderEnd).ToList();//获取分拣单信息
            if (listDetail.Where(_ => string.IsNullOrEmpty(_.GOODSCODE)).Count() > 0)
            {
                return "{success:false,msg:'配方同步中，请过五分钟再操作'}";
            }

            if (lstPrintOrderInfo.Count <= 0)
                return "{success:false,msg:'没有符合条件的订单'}";
            foreach (PrintOrderInfo item in lstPrintOrderInfo)
            {
                item.SaleOrderItem = listDetail.Where(_ => _.SHEETID == item.SHEETID).ToList();
                item.TOTALQTY = listDetail.Where(_ => _.SHEETID == item.SHEETID).Sum(_ => _.QTY);
                item.DIFFQTY = listDetail.Where(_ => _.SHEETID == item.SHEETID && !string.IsNullOrWhiteSpace(_.SKUNAME) && !string.IsNullOrWhiteSpace(_.PRODUCTNAME) &&
                _.SKUNAME.Trim() != _.PRODUCTNAME.Trim()).ToList().Count();
            }
            List<OrderInfo_Print_His> lstOrderInfo_Print_His = GetOrderInfo_Print_His(lstPrintOrderInfo);
            if (Ispreview == "1")//预览不打印
            {
                string strPrintOrderInfo = JsonConvert.SerializeObject(lstPrintOrderInfo[0]);
                sjson = "{success:true,msg:'',info:" + strPrintOrderInfo + "}";
                return sjson;
            }
            int AreaCount = lstPrintOrderInfo.Count(_ => string.IsNullOrEmpty(_.DISTRICT));
            if (AreaCount > 0)
                return "{success:false,msg:'有" + AreaCount + "张订单没有匹配的配送区域,如：" + lstPrintOrderInfo.Where(_ => string.IsNullOrEmpty(_.DISTRICT)).ToList()[0].SHEETID + "'}";
            if (db.AddOrderInfoPrintHis(lstOrderInfo_Print_His))
            {
                string strPrintOrderInfo = JsonConvert.SerializeObject(lstPrintOrderInfo);
                sjson = "{success:true,msg:'',info:" + strPrintOrderInfo + "}";
            }
            else
                sjson = "{success:false,msg:'执行失败'}";

            return sjson;
        }

        public List<OrderInfo_Print_His> GetOrderInfo_Print_His(List<PrintOrderInfo> lstPrintOrderInfo)
        {
            AppUserList model = (AppUserList)Session["UserInfo"];
            List<OrderInfo_Print_His> lstOrderInfo_Print_His = new List<OrderInfo_Print_His>();
            foreach (PrintOrderInfo _PrintOrderInfo in lstPrintOrderInfo)
            {
                OrderInfo_Print_His _OrderInfo_Print_His = new OrderInfo_Print_His();
                _OrderInfo_Print_His.ORDERNO = _PrintOrderInfo.SHEETID;
                _OrderInfo_Print_His.PRINTUSERID = model.USERID;
                _OrderInfo_Print_His.PRINTUSERNAME = model.USERNAME;
                _OrderInfo_Print_His.PRINTDATE = DateTime.Now;
                lstOrderInfo_Print_His.Add(_OrderInfo_Print_His);
            }
            return lstOrderInfo_Print_His;
        }

    }
}
